import { PersonEditDto } from 'shared/service-proxies/service-proxies';
import { PersonServiceProxy, CreateOrUpdatePersonInput } from '@shared/service-proxies/service-proxies';
import { Component, ViewChild, Injector, Output, EventEmitter, ElementRef, OnInit } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { AppComponentBase } from '@shared/app-component-base';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'app-create-person',
  templateUrl: './create-person.component.html'
})
export class CreatePersonComponent extends AppComponentBase implements OnInit {

  @ViewChild('createPersonModal') modal: ModalDirective;
  @ViewChild('modalContent') modalContent: ElementRef;
  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
  active = false;
  saving = false;
  person: PersonEditDto = null;

  constructor(
    injector: Injector,
    private _personService: PersonServiceProxy) {
    super(injector);
  }

  ngOnInit() {
  }


  /**
   * 模态框显示方法
   *
   * @memberof CreatePersonComponent
   */
  show(): void {
    this.active = true;
    this.modal.show();
    this.person = new PersonEditDto();
  }

  /**
   *在模态框显示时
   *
   * @memberof CreatePersonComponent
   */
  onShown(): void {
    $.AdminBSB.input.activate($(this.modalContent.nativeElement));
  }

  /**
   *保存方法
   *
   * @memberof CreatePersonComponent
   */
  save(): void {
    // TODO: Refactor this, don't use jQuery style code
    this.saving = true;
    const input = new CreateOrUpdatePersonInput();
    input.person = this.person;
    this._personService.createOrUpdatePerson(input)
      .pipe(finalize(() => { this.saving = false; }))
      .subscribe(() => {
        this.notify.info(this.l('SavedSuccessfully'));
        this.close();
        this.modalSave.emit(null);
      });
  }

  /**
   *关闭模态框
   *
   * @memberof CreatePersonComponent
   */
  close(): void {
    this.active = false;
    this.modal.hide();
  }

}
